package com.nbicc.common.utils;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class XmlUtils {

    /**
     *
     * @param bodyString
     * @param length        截取长度
     * @return
     */
    public static String bodyTextParse(String bodyString , Integer length){
        String bodyText = bodyTextParse(bodyString);
        if(length == null || length > bodyText.length()){
            return bodyText;
        }
        return bodyTextParse(bodyString).substring(0 , length);
    }

    public static String bodyTextParse(String bodyString){
        bodyString = "<root>" + bodyString + "</root>";
        StringBuffer sb = new StringBuffer();
        StringReader read = new StringReader(bodyString);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new InputSource(read) );
            Element ele = document.getRootElement();
            parserNode(ele , sb);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void parserNode(Element ele , StringBuffer sb){
        sb.append(ele.getText().trim());
        List<Element> eleList = ele.elements();
        //递归遍历父节点下的所有子节点
        for(Element e : eleList){
            parserNode(e,sb);
        }
    }

    /**
     * 从富文本中    解析图片id
     * @param imgStr
     * @return
     * @throws Exception
     */
    public static Set<String> imgSrcParse(String imgStr){
        Set<String> imgIds = new HashSet<>();
        if(StringUtils.isEmpty(imgStr)){
            return imgIds;
        }
        imgStr = "<root>" + imgStr + "</root>";
        StringReader read = new StringReader(imgStr);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new InputSource(read) );
            List<Element> nodes = document.selectNodes("//img");
            for (Element e : nodes) {
                Attribute src = e.attribute("src");
                if(src != null){
                    imgIds.add(src.getValue());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            return imgIds;
        }
    }

}
